package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
//@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

   @Autowired
   private WmNewsMaterialMapper wmNewsMaterialMapper;

   @Autowired
   private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService autoScanService;

    @Autowired
    private WmNewsTaskService taskService;
    /**
     * 分页查询文章的别表数据
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        WmUser wmUser = WmThreadLocalUtil.getUser();
        if(null == wmUser){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //1. 检查分页参数
        dto.checkParam();

        //2. 构建分页参数
        IPage<WmNews> page = new Page(dto.getPage(), dto.getSize());

        //3. 构建查询的条件
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        if(dto.getStatus() != null){
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        if(null != dto.getBeginPubDate() && null != dto.getEndPubDate()){
            lambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }

        if(null != dto.getChannelId()){
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }

        if(StringUtils.isNotEmpty(dto.getKeyword())){
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }

        lambdaQueryWrapper.eq(WmNews::getUserId, wmUser.getId());

        //4. 查询
        page(page, lambdaQueryWrapper);


        // 封装返回结果
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int)page.getTotal());

        responseResult.setData(page.getRecords());

        return responseResult;
    }

    /**
     * 保存文章的方法
     *
     * @param dto
     * @return
     */
    @Override
    @GlobalTransactional
    public ResponseResult submitNews(WmNewsDto dto) throws Exception {
        if(null == dto || StringUtils.isEmpty(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //保存或更新文章
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //补充其他数据
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable((short)1);
        wmNews.setSubmitedTime(new Date());

        //对封面自动的类型进行处理
        if(dto.getType() == -1){
            wmNews.setType(null);
        }

        if(null != dto.getImages() && dto.getImages().size() > 0){
            String images = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(images);
        }

        saveOrUpdateWmNew(wmNews);

        //如果用户保存的草稿则结束请求
        if(dto.getStatus().equals(WmNews.Status.NORMAL)){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //从内容中抽取所有的图片数据
        List<String> urls = ectractUrlInfo(dto.getContent());

        //保存内容中的图片和素材之间的关联关系
        saveRelativeInfoForContent(wmNews,urls,(short)0);

        //保存封面图片与素材之间的关系
        saveRelativeInfoForCover(wmNews, dto, (short)1, urls);


        //文中发布完成-进入审核环节
        //autoScanService.autoScanWmNews(wmNews.getId());
        taskService.addWmNewsToTask(wmNews);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存封面图片与素材之间的关系
     * @param wmNews
     * @param dto
     * @param type
     */
    private void saveRelativeInfoForCover(WmNews wmNews, WmNewsDto dto, short type, List<String> urls) {
        //封面的图片-单图 多图 无图
        List<String> images = dto.getImages();
        //封面的图片属于自动
        if(dto.getType() == -1){
            if(urls.size() > 3){
                images = urls.stream().limit(3).collect(Collectors.toList());
                wmNews.setType((short)3);
            }else if(urls.size() >=1){
                images = urls.stream().limit(1).collect(Collectors.toList());
                wmNews.setType((short)1);
            }else {
                wmNews.setType((short) 0);
            }
        }

        //更新WmNWE的数据
        updateById(wmNews);

        //保存封面图片和素材之间的关系
        saveRelativeInfo(wmNews, images, type);
    }

    private void saveRelativeInfoForContent(WmNews wmNews, List<String> urls, short type) {
        saveRelativeInfo(wmNews, urls, type);
    }

    private void saveRelativeInfo(WmNews wmNews, List<String> urls, short type){
        //判断内容中是否有图片 如果有则保存关系
        if(urls.size() > 0){
            // 对urls里面的额图片的地址进行去重-文章中可能会有重复的图片
            urls = urls.stream().distinct().collect(Collectors.toList());
            // 根据url查询素材对象
            WmUser wmUser = WmThreadLocalUtil.getUser();
            if(null == wmUser){
                throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
            }
            List<WmMaterial> wmMaterials = wmMaterialMapper
                    .selectList(Wrappers.<WmMaterial>lambdaQuery()
                            .in(WmMaterial::getUrl, urls)
                            .eq(WmMaterial::getUserId, wmUser.getId()));
            // 判断素材数据再使用的过程中是否被删除了
            if(null == wmMaterials || urls.size() != wmMaterials.size()){
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }
            //保存素材和文章之间的关系
            List<Integer> ids = wmMaterials.stream().map(item -> item.getId()).collect(Collectors.toList());
            wmNewsMaterialMapper.saveRelations(wmNews.getId(), ids, type);
        }
    }

    /**
     * 从内容中抽取所有的图片数据
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<Map> list = JSON.parseArray(content, Map.class);
        List<String> result = new ArrayList<>();
        for (Map map : list) {
            if("image".equals(map.get("type"))){
                result.add(map.get("value").toString());
            }
        }

        return result;
    }

    /**
     * 完成文章数据的保存或者更新
     * @param wmNews
     */
    private void saveOrUpdateWmNew(WmNews wmNews) {
        if(null != wmNews.getId()){
            //更新
            //删除关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));

            //更新文章数据到文章表
            updateById(wmNews);
        }else{
            //新增
            save(wmNews);
        }

    }
}
